﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.RemoteEventBus;
using Abp.Runtime.Caching;
using FwProject.Core.Distribution;
using FwProject.Core.Restaurant;
using FwProject.Distribution;
using FwProject.Distribution.Dto;
using FwProject.Restaurant;
using FwProject.Users;
using Microsoft.EntityFrameworkCore;
using Castle.Core.Logging;
using FwProject.PublicService.JPush;
using FwProject.Authorization.Users;
using FwProject.Comm;
using FwProject.JPush.JPushModel;
using FwProject.Core.SettlementInfoModel;
using Abp;

namespace FwProject.RemoteEventBus
{

    [RemoteEventHandler(ForType = RemoteTypeHelp.TYPEDistributionBySettlementInfo, ForTopic = RemoteTypeHelp.TopicSettlementInfoDistribution)]
    public class DistributionBySettlementInfo : IRemoteEventHandler, ITransientDependency
    {
        public readonly ICacheManager _catchmanager;
        public readonly IJPushAppservice _jPushAppservice;
        private readonly IRepository<DistributionInfo, Guid> _repositoryDistributionInfo;
        private readonly IRepository<SettlementInfo, Guid> _repositorySettlementInfo;
        private readonly IRepository<User, long> _userRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        public ILogger logging { get; set; }
        public IGuidGenerator _guid { get; set; }
        public DistributionBySettlementInfo(ICacheManager catchmanager, IJPushAppservice jPushAppservice,
                                          IRepository<DistributionInfo, Guid> repositoryDistributionInfo,
                                          IUserAppService userAppService, IRepository<SettlementInfo, Guid> repositorySettlementInfo,
                                           IRepository<User, long> userRepository,
                                           IUnitOfWorkManager unitOfWorkManager)
        {
            _userRepository = userRepository;
            _repositoryDistributionInfo = repositoryDistributionInfo;
            _repositorySettlementInfo = repositorySettlementInfo;
            _catchmanager = catchmanager;
            _jPushAppservice = jPushAppservice;
            logging = NullLogger.Instance;
            _userRepository = userRepository;
            _guid = SequentialGuidGenerator.Instance;
            _unitOfWorkManager = unitOfWorkManager;


        }
        [UnitOfWork]
        public void HandleEvent(RemoteEventArgs eventArgs)
        {
            using (var unitOfWork = _unitOfWorkManager.Begin())
            {
                try
                {
                    var Id = Guid.Parse(eventArgs.EventData.Data[RemoteTypeHelp.MODELID].ToString());
                    
                    var f = _repositoryDistributionInfo.GetAllIncluding(o => o.RestaurantInfoModel, o => o.DistributionInfoListDetails).Where(o => o.Id == Id).FirstOrDefault();
                    if (f != null)
                    {
                        if (f.RestaurantInfoModel.BalanceWay == Core.Restaurant.BalanceWayEnum.日结)
                        {
                            if (f.SettlementId.HasValue == false)
                            {
                                SettlementInfo settlementInfo = new SettlementInfo();
                                settlementInfo.Id = _guid.Create();
                                f.SettlementId = settlementInfo.Id;
                                ///同步计算
                                //Parallel.ForEach(f.DistributionInfoListDetails.AsParallel(), item =>
                                //{
                                //    item.PricesId = f.SettlementId.Value;
                                //});

                                foreach (var item in f.DistributionInfoListDetails)
                                {
                                    item.PricesId = f.SettlementId.Value;
                                }
                                settlementInfo.Totalprice = f.TotalPrice;
                                settlementInfo.Actualprice = f.TotalPrice;
                                settlementInfo.Discountprice = 0;
                                settlementInfo.Restaurantid = f.Restaurantid;
                                settlementInfo.ExamineStatus = Core.SettlementInfoModel.ExamineStatus.已审核;
                                settlementInfo.EmployeeDriverid = f.CreatorUserId.Value;
                                settlementInfo.DeliveryDate = $"（日结）{DateTime.Now.ToString("yyyy-MM-dd")}";
                                settlementInfo.FactoryinfoId = f.FactoryinfoId;
                                settlementInfo.BeginTime = f.CreationTime;
                                settlementInfo.EndTime = f.CreationTime;
                                settlementInfo.BalanceWayEnum = Core.Restaurant.BalanceWayEnum.日结;
                                settlementInfo.RemarksConten = $"系统生成";
                                settlementInfo.CreatorUserId = f.CreatorUserId;
                                _repositorySettlementInfo.Insert(settlementInfo);
                            }

                            else
                            {
                                var m = _repositorySettlementInfo.Get(f.SettlementId.Value);
                                m.Totalprice = f.TotalPrice;
                                m.Actualprice = f.TotalPrice;
                                m.Discountprice = 0;
                            }
                        }
                    }
                }
                catch (Exception exe)
                {
                   
                    logging.Error($"{nameof(DistributionBySettlementInfo)}", exe);

                }
                finally
                {
                    logging.Info($"{nameof(DistributionBySettlementInfo)}");
                }

                unitOfWork.Complete(); 
            }
        }
    }
}
